from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here.

def index(request):


    from django.db.models import Avg, Sum, Max, Min, Count, F,Q

    # 1 查询每个作者的姓名以及出版的书的最高价格
    # ret = models.Author.objects.annotate(a=Max('book__price')).values('name','a')

    # 2 查询作者id大于2作者的姓名以及出版的书的最高价格
    # ret = models.Author.objects.filter(id__gt=2).annotate(max=Max('book__price')).values('name','max')

    # 3 查询作者id大于2或者作者年龄大于20岁的,必须是女作者的姓名以及出版的书的最高价格
    # ret = models.Author.objects.filter(Q(Q(id__gt=2)|Q(age__gt=20))&Q(sex='女')).annotate(a=Max('book__price')).values('name','a')

    # 4 查询每个作者出版的书的最高价格 的平均值
    # ret = models.Author.objects.values('id').annotate(a=Max('book__price')).values('a').aggregate(x=Avg('a'))

    # 5 每个作者出版的所有书的最高价格以及最高价格的那本书的名称
    # ret = models.Author.objects.annotate(a=Max('book__price')).values('a','book__title')

    # print(ret) #{'x': 156.25}




    return HttpResponse('ok')


# import pymysql
# conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='666',database='orm02',charset='utf8')
# cursor = conn.cursor()
# cursor.execute('select * from app01_book;')
# cursor.fetchall()


def showbooks(request):

    book_objs = models.Book.objects.all()

    return render(request,'showbooks.html',{'book_objs':book_objs})

from django import forms

class AddBookForm(forms.Form):
    title = forms.CharField(
        label='书名',
    )
    price=forms.DecimalField(
        label='价格',
        max_digits=5,
        decimal_places=2 , #999.99
        # widget = forms.TextInput(attrs={'class':'form-control'}),
    )
    publishDate=forms.CharField(

        label='出版日期',
        widget=forms.TextInput(attrs={'type':'date'}),

    )
    # publishs_id = forms.ChoiceField(
    #     choices=models.Publish.objects.all().values_list('id','name'),  #[(),()]
    # )
    # authors=forms.MultipleChoiceField(
    #     choices=models.Author.objects.all().values_list('id','name')
    #
    # )

    publishs = forms.ModelChoiceField(
        queryset=models.Publish.objects.all(),
    )
    authors = forms.ModelMultipleChoiceField(
        queryset=models.Author.objects.all(),

    )

    # csrfmiddlewaretoken = forms.ChoiceField
    # 批量添加属性样式
    def __init__(self,*args,**kwargs):

        super().__init__(*args,**kwargs)

        for field_name,field in self.fields.items(): #orderdict(('username',charfield对象))

            field.widget.attrs.update({'class':'form-control'})



# models.Book.objects.create(
#
# **{'title2':'xx'}
# )

def addbook(request):
    if request.method == 'GET':
        # all_publish = models.Publish.objects.all()
        # all_authors = models.Author.objects.all()
        #
        # return render(request,'addbook.html',{'all_publish':all_publish,'all_authors':all_authors})
        book_obj = AddBookForm()
        return render(request,'addbook.html',{'book_obj':book_obj})



    else:


        book_obj = AddBookForm(request.POST)
        print(request.POST)
        if book_obj.is_valid():
            print(book_obj.cleaned_data)
            #{'title': '金瓶梅2', 'price': Decimal('11'),
            # 'publishDate': '2019-10-03', 'publishs': '3', 'authors': ['1', '5']}

            #{'title': '金瓶梅4', 'price': Decimal('22'), 'publishDate': '2019-10-11', 'publishs': <Publish: 红浪漫出版社>,
            # 'authors': <QuerySet [<Author: 陈硕>, <Author: 海狗>, <Author: 子文>]>}
            data = book_obj.cleaned_data
            authors = data.pop('authors')

            new_book = models.Book.objects.create(
                **data
                # publishs = 对象
            )
            new_book.authors.add(*authors)

            # return HttpResponse('ok')
            return redirect('showbooks')
        else:
            return render(request,'addbook.html',{'book_obj':book_obj})


        # authors = request.POST.getlist('authors')
        # print('authors',authors)
        # data = request.POST.dict()
        # data.pop('csrfmiddlewaretoken')
        # data.pop('authors')
        #
        # print(data)
        #
        # new_book_obj = models.Book.objects.create(**data)
        # new_book_obj.authors.add(*authors)

        # '''
        # {'title': '金瓶梅', 'price': '200', 'publishDate': '2019-10-20', 'publishs': '3'}
        # '''
        # return redirect('showbooks')


# def delbook(request,book_id):
#
#     models.Book.objects.filter(pk=book_id).delete()
#     return redirect('showbooks')


# def delbook(request):
#
#     book_id = request.GET.get('book_id')
#     models.Book.objects.filter(pk=book_id).delete()
#     return redirect('showbooks')

from django.http import JsonResponse
#ajax删除
def delbook(request):

    book_id = request.POST.get('book_id')
    print('book_id',book_id)
    models.Book.objects.filter(pk=book_id).delete()

    data = {'status':1}

    return JsonResponse(data)

def editbook(request,book_id):
    old_objs = models.Book.objects.filter(pk=book_id) #

    if request.method == 'GET':
        all_publish = models.Publish.objects.all()
        all_authors = models.Author.objects.all()
        old_obj = old_objs.first()

        return render(request,'editbook.html',{'all_publish':all_publish,'all_authors':all_authors,'old_obj':old_obj})
    else:
        authors = request.POST.getlist('authors')
        print('authors',authors)
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        data.pop('authors')

        print(data)

        old_objs.update(**data)
        old_objs.first().authors.set(authors)

        return redirect('showbooks')
